package com.shuqi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.RedDotProvider;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.controller.AccountController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.VersionShowDao.VersionShowEnum;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.AccountInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

public class AccountActivity extends ActivityBase implements IEventListener, OnClickListener {

    /** 返回账户页的时候，是否需要刷新账户页：绑定/解绑操作完成，修改密码完成，修改资料完成，充值完成……需要更改 */
    private static boolean isNeedRefreshAccountPage = false;

    private final String logTag = "AccountActivity";
    private AccountController controller;
    private AccountInfo accountInfo;

    // private ImageView refreshIV;
    private TextView cancelAutoBuyTxtView = null;

    private final int Mgs_initView = 0; // 初始化用户资料
    private final int Mgs_Data_NetOk = 1; // 资料获取成功
    private final int MGS_DATA_USERSTATEOK = 2; // 资料获取成功
    private final int Mgs_Data_error = 3;// 资料获取失败

    private CommonTitle mTitle;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Mgs_initView:
                    activityLogicForward();
                    break;
                case Mgs_Data_NetOk:
                    activityInitData();
                    // stopLoading();
                    break;
                case MGS_DATA_USERSTATEOK:
                    onCheckUserStatePassed();
                    break;
                case Mgs_Data_error:
                    onNetError();
                    // stopLoading();
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        controller =
                (AccountController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_ACCOUNT, this);
        controller.addEventListener(this);
        setContentView(R.layout.act_account);

        // refreshIV = (ImageView) findViewById(R.id.account_top_refresh);
        cancelAutoBuyTxtView = (TextView) findViewById(R.id.account_cancel_auto_buy);

        handler.sendEmptyMessage(Mgs_initView); // 通知初始化View
        StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_PAGE_ENTER);

    }

    @Override
    protected void onResume() {
        if (isNeedRefreshAccountPage) {
            refresh();
        }

        mTitle = (CommonTitle) findViewById(R.id.title);

        boolean isShowSettingRed = SharedPreferenceUtil.isSoftUpdate(this);
        boolean newPullVersion =
                RedDotProvider.getInstance().isShowRedDot(VersionShowEnum.new_pull_version_red_dot);

        if (isShowSettingRed&&newPullVersion) {
            mTitle.setRightImage(R.drawable.icon_account_setting_red_point_selector);
        } else {
            mTitle.setRightImage(R.drawable.icon_account_setting_selector);
        }

        super.onResume();
    }

    /** 返回账户页的时候，是否需要刷新账户页：绑定/解绑操作完成，修改密码完成，修改资料完成，充值完成……需要更改 */
    public static void callRefreshAccountOnResume() {
        Log4an.i("AccountActivity", "callRefreshAccountOnResume");
        isNeedRefreshAccountPage = true;
    }

    /**
     * 刷新当前页面
     */
    private void refresh() {


        controller.handle(0, ""); // 通知加载数据
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setImageListener(this);
        // findViewById(R.id.account_top_left).setOnClickListener(this);
        // findViewById(R.id.account_top_setting).setOnClickListener(this);
        UserInfo info = MyAccountManager.getInstance(getApplicationContext());
        if (MyAccountManager.isGuestUser(info)) {
            jumpToLogin();
            return;
        } else {
            showAccountPageData(info);
            Log4an.i(logTag, "onCreate: 验证前：展示用户资料");
        }


        // 小红点控制
        View redPoint = findViewById(R.id.account_my_favorit_red_point);
        if (redPoint != null) {

            boolean isShow =
                    RedDotProvider.getInstance().isShowRedDot(VersionShowEnum.my_favorite_red_dot);

            if (isShow)
                redPoint.setVisibility(View.VISIBLE);
            else
                redPoint.setVisibility(View.GONE);
        }

        refresh();
    }

    @Override
    public void activityInitData() {
        if (accountInfo != null && "200".equals(accountInfo.getServerState())) {
            // 1会员，2准会员
            if ("1".equals(accountInfo.getGrade())) { // 会员
                if ("1".equals(accountInfo.getValidate())) { // 会员身份验证通过
                    Log4an.e(logTag, "会员，验证通过：" + accountInfo.getValidate());
                    handler.sendEmptyMessage(MGS_DATA_USERSTATEOK);
                } else { // 会员验证失败
                    Log4an.e(logTag, "会员，验证失败，需要登录：" + accountInfo.getValidate());
                    jumpToLogin();
                    if(!TextUtils.isEmpty(accountInfo.getValidateMessage())){
                        showMsg(accountInfo.getValidateMessage());
                    }
                }
            } else if ("2".equals(accountInfo.getGrade())) { // 准会员
                String code = accountInfo.getUniqueCode();
                if ("200".equals(code)) { // 会员验证通过
                    Log4an.e(logTag, "准会员，验证通过" + accountInfo.getUniqueCode());
                    handler.sendEmptyMessage(MGS_DATA_USERSTATEOK);
                } else if ("201".equals(code)) { // 准会员验证通过，绑定sn
                    Log4an.e(logTag, "准会员，验证通过，绑定sn：" + accountInfo.getUniqueCode());
                    handler.sendEmptyMessage(MGS_DATA_USERSTATEOK);
                } else if ("202".equals(code)) { // 准会员验证通过，新分配userId
                    Log4an.e(logTag, "准会员验证通过，分配新的userid：" + accountInfo.getUniqueCode());
                    MyAccountManager.onLoginSuccess(getApplicationContext(), accountInfo.getUser());
                    handler.sendEmptyMessage(MGS_DATA_USERSTATEOK);
                } else if ("203".equals(code)) { // 准会员验证失败，下次需要重新验证
                    Log4an.e(logTag, "准会员验证，服务器绑定sn失败，下次需要重新验证" + accountInfo.getUniqueCode());
                    handler.sendEmptyMessage(MGS_DATA_USERSTATEOK);
                } else { // 准会员验证失败，降级为800万身份
                    MyAccountManager.changeGusetUser(getApplicationContext());
                    jumpToLogin();
                    if(!TextUtils.isEmpty(accountInfo.getUniqueMessage())){
                        showMsg(accountInfo.getUniqueMessage());
                    }
                    Log4an.e(logTag, "验证失败：" + code + "，降级为800万");
                }
            } else {
                jumpToLogin();
                Log4an.e(logTag, "error userGrade grade=" + accountInfo.getGrade());
            }
        } else {
            UserInfo info = MyAccountManager.getInstance(this);
            if (MyAccountManager.isGuestUser(info)) {
                jumpToLogin();
            }
        }
    }

    /***
     * 当检查账户失败的时候的操作 打开登录页面
     */
    private void jumpToLogin() {
        ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
            public void run() {
                LoginActivity.openVerifyForResult(AccountActivity.this, -1);
                finish();
            }
        }, 400);
    }

    /** 网络失败 */
    private void onNetError() {
        if (!isFinishing()) {
            showMsg("网络异常");
            if (needLogin()) {
                jumpToLogin();
            } else {
                updateClickPermissions(MyAccountManager.getInstance(getApplicationContext(), true));
            }
        }
    }

    /** 是否需要跳转登陆页面 */
    private boolean needLogin() {
        UserInfo userInfo = MyAccountManager.getInstance(getApplicationContext());
        return MyAccountManager.isGuestUser(userInfo);
    }

    /**
     * 更新用户资料/展示账户页资料
     * 
     * @param isFirstShow true显示默认账户，false联网得到的账户信息
     */
    private void onCheckUserStatePassed() {
        UserInfo userInfo = accountInfo.getUser();
        MyAccountManager.onLoginSuccess(getApplicationContext(), userInfo);
        showAccountPageData(userInfo);
        Log4an.i(logTag, "onCheckUserStatePassed: 验证通过：展示最新的用户资料");
    }

    /***
     * 设置不同用户是否可以点击
     * 
     * @param userInfo
     */
    private void updateClickPermissions(UserInfo userInfo) {
        Log4an.i(
                logTag,
                "updateClickPermissions: user="
                        + (userInfo == null ? "null" : (userInfo.getUserId() + userInfo
                                .getUserState())));
        if (MyAccountManager.isGuestUser(userInfo)
                || MyAccountManager.isNeedCheckUserState(userInfo)) {
            Log4an.i(logTag, "updateClickPermissions: 禁止点击");
            findViewById(R.id.account_top_show).setOnClickListener(null);
            findViewById(R.id.account_binner_bind).setOnClickListener(null);
            findViewById(R.id.account_binner_pay).setOnClickListener(null);
            findViewById(R.id.account_binner_buyhistory).setOnClickListener(null);
            findViewById(R.id.account_binner_payhistory).setOnClickListener(null);
            findViewById(R.id.account_recentlyViewed_tv).setOnClickListener(null);
            findViewById(R.id.account_my_favorit_layout).setOnClickListener(null);
            cancelAutoBuyTxtView.setOnClickListener(null);
        } else {
            Log4an.i(logTag, "updateClickPermissions: 允许点击");
            findViewById(R.id.account_top_show).setOnClickListener(this);
            findViewById(R.id.account_binner_bind).setOnClickListener(this);
            findViewById(R.id.account_binner_pay).setOnClickListener(this);
            findViewById(R.id.account_binner_buyhistory).setOnClickListener(this);
            findViewById(R.id.account_binner_payhistory).setOnClickListener(this);
            findViewById(R.id.account_recentlyViewed_tv).setOnClickListener(this);
            findViewById(R.id.account_my_favorit_layout).setOnClickListener(this);
            cancelAutoBuyTxtView.setOnClickListener(this);
        }
    }

    /***
     * 展示账户页资料
     */
    private void showAccountPageData(UserInfo userInfo) {
        findViewById(R.id.account_top_scroll).setVisibility(View.VISIBLE);
        Log4an.i(logTag, "显示账户信息");

        if (userInfo != null) {
            TextView tvName = (TextView) findViewById(R.id.account_top_username);
            TextPaint tp = tvName.getPaint();
            tp.setFakeBoldText(true);

            tvName.setText(userInfo.getNickName());

            if (("2").equals(userInfo.getGender())) {
                ((TextView) findViewById(R.id.account_top_username))
                        .setCompoundDrawablesWithIntrinsicBounds(0, 0,
                                R.drawable.icon_account_gender_girl, 0);
            } else {
                ((TextView) findViewById(R.id.account_top_username))
                        .setCompoundDrawablesWithIntrinsicBounds(0, 0,
                                R.drawable.icon_account_gender_boy, 0);
            }

            TextView bindTips = (TextView) findViewById(R.id.account_top_bindtips);
            if (!MyAccountManager.isVipUser(userInfo)) {
                bindTips.setVisibility(View.VISIBLE);
                bindTips.setText("您还未绑定过任何账号");
            } else {
                bindTips.setVisibility(View.GONE);
            }
            int level = MyAccountManager.checkUserSafeLevel(userInfo);
            TextView safe = (TextView) findViewById(R.id.account_binner_bind_safe);
            safe.setText(Html.fromHtml(getUserSafeLevelHtmlText(level)));

            String balance = userInfo.getBalance();
            balance = TextUtils.isEmpty(balance) ? "0" : balance;
            ((TextView) findViewById(R.id.account_binner_pay_balance)).setText(Html
                    .fromHtml(getBalanceHtmlText(balance)));
        }
        updateClickPermissions(userInfo);
    }

    private String getBalanceHtmlText(String balance) {
        return "<font color=#14be7d>" + balance + " </font>书豆";
    }

    private String getUserSafeLevelHtmlText(int level) {
        if (level == UserInfo.USERSAFELEVEL_HIGH) {
            return "账户安全级别：" + "<font color=#14be7d>高</font>";
        } else if (level == UserInfo.USERSAFELEVEL_COMMON) {
            return "账户安全级别：" + "<font color=#ffa01b>中</font>";
        } else {
            return "账户安全级别：" + "<font color=#ff361b>低</font>";
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                // MainActivityGroup.show(this, true);
                BookShelfActivity.show(this, true);
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.title_right: {
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_PAGE_CLICK_INFO);
                Intent intent = new Intent(this, UserSettingActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, AccountActivity.this);
                StatisticsUtils.onEvent(this, StatisticsEventID.ACCOUNT_USER_SETTING);
            }
                break;
            // case R.id.account_top_refresh:
            // StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_PAGE_REFRESH);
            // refresh();
            // break;
            case R.id.retry:
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        refresh();

                    }
                });
                break;
            case R.id.account_top_show: {
                Intent intent = new Intent(this, AccountDataModifyActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, AccountActivity.this);
            }
                break;
            case R.id.account_binner_bind:
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_PAGE_ENTER);
                AccountBindActivity.show(this);
                break;
            case R.id.account_binner_pay: {
                Intent intent = new Intent(this, PayActivity.class);
                ActivityManager.getInstance().startNextActivityForResult(intent,
                        Activity.RESULT_CANCELED, AccountActivity.this);
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BINNER_PAY);
            }
                break;
            case R.id.account_binner_buyhistory: {
                Intent intent = new Intent(AccountActivity.this, PurchaseHistoryActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);
                StatisticsUtils.onEvent(AccountActivity.this, StatisticsEventID.ACCOUNT_PAYHISTORY);
                // Intent intent = new Intent(this, PayHistoryActivity.class);
                // ActivityManager.getInstance().startNextActivity(intent, AccountActivity.this);
                // StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_PAYHISTORY);
            }
                break;
            case R.id.account_binner_payhistory: {
                Intent intent = new Intent(this, RechargesActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, AccountActivity.this);
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_RECHARGES);
            }
                break;
            case R.id.account_my_favorit_layout: {
                RedDotProvider.getInstance().hideRedDot(VersionShowEnum.my_favorite_red_dot);
                View redPoint = findViewById(R.id.account_my_favorit_red_point);
                if (redPoint != null)// 同时界面不显示红点
                    redPoint.setVisibility(View.GONE);

                Intent intent = new Intent(this, MyFavoritActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);

                StatisticsUtils.onEvent(this, StatisticsEventID.MYCOLLECTION_CLICKBOOK);
                break;
            }
            case R.id.account_recentlyViewed_tv: {
                Intent intent = new Intent(AccountActivity.this, BrowsingHistoryActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);
                StatisticsUtils.onEvent(AccountActivity.this,
                        StatisticsEventID.BOOKSHELF_RECENTLY_VIEWED);
            }
                break;
            case R.id.account_cancel_auto_buy: {
                Intent intent = new Intent();
                intent.setClass(this, CancleBuyActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);
                StatisticsUtils.onEvent(AccountActivity.this,
                        StatisticsEventID.BOOKCONTENT_CANCEL_AUTO_BUY);
            }
                break;
            default:
                break;
        }
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:// 读取数据 写处理逻辑
                accountInfo = (AccountInfo) data;
                if (accountInfo != null) {
                    handler.sendEmptyMessage(Mgs_Data_NetOk);
                    isNeedRefreshAccountPage = false;
                } else {
                    handler.sendEmptyMessage(Mgs_Data_error);
                }
                Log4an.i(logTag, accountInfo.toString());
                break;
            default:
                handler.sendEmptyMessage(Mgs_Data_error);
                Log4an.i(logTag, "error event=" + event);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            // MainActivityGroup.show(this, true);
            BookShelfActivity.show(this, true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /** 底部跳转绑定弹出框 */
    private BottomDialog dialogBinding = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            UserInfo userInfo = MyAccountManager.getInstance(this, true);
            if (!MyAccountManager.isVipUser(userInfo) && !MyAccountManager.isGuestUser(userInfo)) {
                showBottomDialog();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /** 显示底部弹出框 */
    private void showBottomDialog() {
        if (this.dialogBinding == null) {
            View viewv = View.inflate(this, R.layout.account_safety_tips, null);
            this.dialogBinding = new BottomDialog(this, viewv);
            this.initDialogBindingDialog(viewv);
            viewv.setOnClickListener(this);
        }
        this.dialogBinding.show();
    }

    /**
     * 事件响应
     */
    private void initDialogBindingDialog(View view) {
        view.findViewById(R.id.binding_account).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AccountBindActivity.show(AccountActivity.this);
                if (dialogBinding != null) {
                    dialogBinding.dismiss();
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (controller != null) {
            controller.onDestroy();
        }
        super.onDestroy();
    }

    /**
     * 打开账户页
     * 
     * @param context
     */
    public static void open(Activity context, boolean isClearTop) {
        UserInfo user = MyAccountManager.getInstance(context);
        if (MyAccountManager.isNeedCheckUserState(user)) {
            LoginActivity.openLoginForResult(context,-1);
        } else {
            Intent intent = new Intent(context, AccountActivity.class);
            if (isClearTop) {
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
            ActivityManager.getInstance().startNextActivity(intent, context);
        }
    }

}
